import { createVNode, render } from 'vue'
import LoadingConstructor from './loading.vue'

// TODO: Since Notify.ts is basically the same like this file. So we could do some encapsulation against them to reduce code duplication.

const loading: any = function(options: boolean, message: string = '加载中...') {
  const props = {
    loading: options,
    message: message
  }

  let appendTo: HTMLElement | null = document.body

  const container = document.createElement('div')

  const vm = createVNode(LoadingConstructor, props, null)

  // clean message element preventing mem leak
  vm.props!.onUnmounted = () => {
    render(null, container)
    // since the element is destroy, then the VNode should be collected by GC as well
    // we do not want cause any mem leak because we have returned vm as a reference to users
    // so that we manually set it to false.
  }

  render(vm, container)
  // instances will remove this item when close function gets called. So we do not need to worry about it.
  appendTo.appendChild(container!)

  //   return () =>(vm.component!.proxy as ComponentPublicInstance<{ loading: boolean }>).loading = false
  return () => render(null, container)
}

export default loading
